import { Scene, Vector3 } from "three";

let segmentDirection = new Vector3()
let pointDirection = new Vector3()
/**
 * 判断点是否在线段上，不包括首尾点
 * @param point 
 * @param segmentStart 
 * @param segmentEnd 
 * @returns 
 */
export function pointOnSegment(point: Vector3, segmentStart: Vector3, segmentEnd: Vector3, threshold: number, posOnLine?: Vector3): boolean {
    // 创建向量表示线段的方向
    segmentDirection.subVectors(segmentEnd, segmentStart);

    // 创建向量表示从线段起点到点的方向
    pointDirection.subVectors(point, segmentStart);

    // 计算点到线段的投影长度
    const projectionLength = pointDirection.dot(segmentDirection) / segmentDirection.lengthSq();

    // 如果投影长度小于0或大于1，则点不在线段上
    if (projectionLength <= 0.000001 || projectionLength >= 0.999999) {
        return false;
    }

    // 计算点在线段上的投影点
    const projection = segmentDirection.multiplyScalar(projectionLength).add(segmentStart);
    if (posOnLine) {
        posOnLine.copy(projection);
    }
    // 计算点到投影点的距离
    const distance = point.distanceTo(projection);
    // console.log(distance, threshold)
    // 如果距离小于一个很小的阈值，则点在线段上
    //const threshold = 0.0001;
    return distance < threshold;
}

export function traverseObject<T extends { children: any[] }>(node: any, callback: (next: T) => boolean) {
    //if ( node.visible === false ) return;
    let next = callback(node);
    if ((node as any as Scene).isScene) next = true;
    if (next) {
        const children = [...node.children];
        for (let i = 0, l = children.length; i < l; i++) {
            traverseObject(children[i], callback);
        }
    }
}
